<?php


namespace app\queue\stomp;


use app\queue\BaseConsumer;
use common\model\PlanModel;
use common\model\ReviewRequestModel;
use common\model\ReviewRequestNodeModel;
use Webman\Stomp\Client;

/**
 * 实体发布
 * Class CalculateEntityManHourConsumer
 * @package app\queue\redis
 */
class PlanConfirmEndTimeAutoConfirmConsumer extends BaseConsumer
{
    // 要消费的队列名
    public $queue = 'plan_confirm_end_time_auto_confirm';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * @param $data
     * @return void
     * @throws \Exception
     */
    public function doConsume($data)
    {
        try {
            $planId = $data['plan_id'];
            $confirmTime = $data['confirm_end_time'];
            $plan = model(PlanModel::class)->field('id,project_id')->find($planId);

            if (empty($plan)) {
                return;
            }

            $reviewRequest = model(ReviewRequestModel::class)
                ->where([
                    'project_id' => $plan['project_id'],
                    'link_id' => $plan['id'],
                    'module_id' => module_by_code('plan')['id']
                ])->field('id')->find();
            if (empty($reviewRequest)) {
                return;
            }

            $reviewRequestNode = model(ReviewRequestNodeModel::class)->where(['review_request_id' => $reviewRequest['id']])->field('id,review_request_id,is_reviewed,is_active,confirm_end_time')->find();
            //判定是否审核过了 ,审核过了将不在审核
            if (empty($reviewRequestNode) || ($reviewRequestNode['is_reviewed'] == 'no' && $reviewRequestNode['is_active'] == 'no')) {
                return;
            }

            //判定时间是否大于,如果大于则再次发送 ,如果不大于则更新为确认
            if ($reviewRequestNode['confirm_end_time'] > $confirmTime) {
                $params = [
                    'plan_id' => $plan['id'],
                    'confirm_time' => $reviewRequestNode['confirm_end_time']
                ];
                Client::send("plan_confirm_end_time_auto_confirm", build_queue_data_with_xu($params), $reviewRequestNode['confirm_end_time'] - $confirmTime);
            } else {
                model(ReviewRequestNodeModel::class)->modifyItem([
                    'id' => $reviewRequestNode['id'],
                    'is_reviewed' => 'yes',
                    'is_pass' => "yes",
                    'is_active' => 'no',
                    'reviewed' => time()
                ]);

                model(ReviewRequestModel::class)
                    ->modifyItem(['id' => $reviewRequestNode['review_request_id'], 'is_pass' => "yes", 'is_reviewed' => "yes", 'reviewed' => time(),]);
                model(PlanModel::class)->where(['id' => $planId])->save(['confirm_status' => 'yes']);
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
